
package category

import (
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"strings"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
)


// get categories
func GetList() []map[string]string {
	sql := Core.Sql("fuxiaohei_categories").Order("id ASC").Where("id > 0").Select()
	return Core.Db.All(sql)
}

// get one category
func GetOneById(id string) map[string]string {
	sql := Core.Sql("fuxiaohei_categories").Where("id = ?").Select()
	return Core.Db.One(sql, id)
}

// get one category by slug
func GetOneBySlug(slug string) map[string]string {
	sql := Core.Sql("fuxiaohei_categories").Where("slug = ?").Select()
	return Core.Db.One(sql, slug)
}

// add new category
func AddCategory(data map[string]string) {
	sql := Core.Sql("fuxiaohei_categories", "title,slug,desc").Insert()
	data["title"] = strings.TrimSpace(data["title"])
	data["slug"] = strings.TrimSpace(data["slug"])
	data["desc"] = strings.TrimSpace(data["desc"])
	Core.Db.Exec(sql, data["title"], data["slug"], data["desc"])
}

// update one category by id
func UpdateCategory(id string, data map[string]string) {
	data["title"] = strings.TrimSpace(data["title"])
	data["slug"] = strings.TrimSpace(data["slug"])
	data["desc"] = strings.TrimSpace(data["desc"])
	sql := Core.Sql("fuxiaohei_categories", "title,slug,desc").Where("id = ?").Update()
	Core.Db.Exec(sql, data["title"], data["slug"], data["desc"], id)
}

// check category slug existed
func checkSlugExist(slug string, id string) bool {
	sql := Core.Sql("fuxiaohei_categories", "id").Where("slug = ?").Select()
	data := Core.Db.One(sql, slug)
	if len(data) < 1 {
		return false
	}
	if id != "" {
		if id == data["id"] {
			return false
		}
		return true
	}
	return true
}

// validate category input data
func validateCategoryData(data map[string]string, id string) string {
	if Rt.Validator.IsShorter(data["title"], 2) {
		return "名称至少1个字符"
	}
	if Rt.Validator.IsShorter(data["slug"], 3) {
		return "缩略名至少2个字符"
	}
	if !Rt.Validator.IsASCII(data["slug"]) {
		return "缩略名只能用英文字母，数字和-"
	}
	if checkSlugExist(data["slug"], id) {
		return "缩略名重复"
	}
	return ""
}

// delete one category by id
func DeleteCategory(id string) {
	// change article category
	sql := Core.Sql("fuxiaohei_articles", "category").Where("category = ?").Update()
	Core.Db.Exec(sql, -1, id)
	// delete category
	sql = Core.Sql("fuxiaohei_categories").Where("id = ?").Delete()
	Core.Db.Exec(sql, id)
	// refresh category's article count
	go updateCount()
}

// refresh category's article count
func updateCount() {
	sql := `UPDATE fuxiaohei_categories SET articles = (SELECT count(*) FROM fuxiaohei_articles WHERE fuxiaohei_articles.category = fuxiaohei_categories.id)`
	Core.Db.Exec(sql)
}

